define(['angularAMD'], function (angularAMD) {
    angularAMD.service('mobile14Service', ['$rootScope', '$filter', '$translate', 'config', '$timeout', 'MMWService', '$mdDialog',
        function($rootScope, $filter, $translate, config, $timeout, $MMWService, $mdDialog){
            this.init = function (options) {
                // 原本的列印功能
                function printLabel(data, dialog){
                    //pdf_url = 'http://www.orimi.com/pdf-test.pdf';
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+data.file_path+'&openfile=false&viewbookmark=false&printfile=true&download=false#zoom=page-width';
                    document.getElementById('kmi-pdf-panel').onload = function(){
                        //確定html 都載入完成就設定EventListener
                        var frame = window.frames['kmi-pdf-panel'];
                        frame.document.getElementById('viewerContainer').addEventListener('pagerendered', function(e){
                            //print_msg:$filter('translate')('mrsc09.msg.print_start');
                            $rootScope.showLoading($filter('translate')('common.msg.pagerendered'));
                            $timeout(function(){
                                frame.pdf_print();
                            });
                        });
                        frame.addEventListener('afterprint', function(){
                            $rootScope.hideLoading();
                            dialog.hide();
                        });
                    };
                }

                // Windows 下的列印功能
                // 20190531 modify by Dustdusk for M#58010: 修正未安裝sumatraPDF時會有錯誤、補上透過外部PDF打印標籤的功能
                function printLabelWin(data, dialog){
                    if(config.setting.outsidePDF == 'Y'){
                        // 走外部列印
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }
                        $rootScope.downloadFile(data.file_path, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                            //window.nodeRequire('electron').shell.openItem(dist_path);
                            window.nodeRequire('child_process').exec('@powershell "start -verb print ""'+dist_path+'"""', (err, stdout, stderr) => {
                                if (err) {
                                    console.error(err);
                                    $rootScope.showAlert(err);
                                } else {
                                    dialog.hide();
                                }
                            });
                        });
                    } else {
                        var sumatraPDF = undefined;
                        try{
                            sumatraPDF = window.nodeRequire('sumatra-pdf');
                        }catch(e){}
                        if(sumatraPDF){
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try{
                                RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                            }catch(e){
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if(!fs.existsSync(RuncardPath)){
                                fs.mkdirSync(RuncardPath);
                            }
                            $rootScope.downloadFile(data.file_path, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                                $rootScope.showLoading($filter('translate')('common.msg.pagerendered'));
                                var _fn = sumatraPDF.printToDefault;
                                if(dialog.settings){
                                    _fn = sumatraPDF.printWithSettings
                                }
                                _fn({
                                    path:RuncardPath+'\\RuncardPreview.pdf',
                                    settings:data.width > data.height ? 'landscape':'',
                                    success:function(){
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                        dialog.hide();
                                    },
                                    error:function(error){
                                        $rootScope.hideLoading();
                                        $rootScope.showToast($filter('translate')('common.msg.success'));
                                        dialog.hide();
                                        //console.error(error);
                                    }
                                });
                            });
                        } else {
                            printLabel(data, dialog);
                        }
                    }
                }

                function printLabelMobile(data, dialog){
                    var RuncardPath = window.parent.cordova.file.cacheDirectory;
                    //先下載下來
                    $rootScope.downloadFile(data.file_path, RuncardPath+'RuncardPreview.pdf', function(dist_path){
                        $rootScope.showLoading($filter('translate')('common.msg.pagerendered'));
                        window.resolveLocalFileSystemURL(RuncardPath+'RuncardPreview.pdf', function(dstDirectoryEntry){
                            window.plugins.PrintPDF.print({
                                data: dstDirectoryEntry.toURL(),
                                type: 'File',
                                title: 'temp',
                                success: function(){
                                    $rootScope.hideLoading();
                                    $rootScope.showToast($filter('translate')('common.msg.success'));
                                    dialog.hide();
                                },
                                error: function(error){
                                    $rootScope.hideLoading();
                                    error = JSON.parse(error);
                                    $rootScope.showAlert('Path:'+data.file_path+'<br>Exception:'+error.error);
                                }
                            });
                        }, function(error){
                            $rootScope.hideLoading();
                            window.parent.showAlert('File Read Error Code : '+error.code);
                        });
                    });
                }

                function downloadBTLabelFile(data, dialog){
                    var RuncardPath = window.parent.cordova.file.cacheDirectory;
                    var _file_list = [];
                    data.file_list.forEach(function(_file_path, index){
                        $rootScope.downloadFile('http://'+config.server.ip+':'+config.server.port + _file_path, RuncardPath+'tagPreview_'+index+'.png', function(dist_path){
                            _file_list.push(dist_path);
                            if(_file_list.length == data.file_list.length){
                                checkBTSetting(_file_list, dialog);
                            }
                        });
                    });
                }

                //再呼叫setPrinterInfoAndPrinter之前
                //先呼叫此function 取得uuid
                function checkBTSetting(data, dialog){
                    var _btprinter_settings = localStorage.getItem(config.appName + '_btprinter_settings');
                    if(_btprinter_settings){
                        _btprinter_settings = JSON.parse(_btprinter_settings);

                        setPrinterInfoAndPrinter(data,qc_type,_btprinter_settings)//將_btprinter_settings傳進去

                    }else{
                        $rootScope.showConfirm($filter('translate')('mobile14.msg.not_setting_btprinter'), function(confirm_dialog){
                            confirm_dialog.hide();
                            $mdDialog.serviceDialog('BTPrinterSetting', {callback:function(settings){
      
                                setPrinterInfoAndPrinter(data,qc_type,settings)//將settings傳進去
                            }});
                        });
                    }
                }

                function printBTLabelMobile(btprinter_settings, data, dialog){
                    //連上藍芽印表機
                    printerHelper.connectPeripheral(function(){
                        var _p = 0;
                        data.forEach(function(file_path){
                            window.resolveLocalFileSystemURL(file_path, function(dstDirectoryEntry){
                                $rootScope.hideLoading();
                                dstDirectoryEntry.file(function (file){
                                    var reader = new FileReader();
                                    reader.onloadend = function(e){
                                        var _temp_base64 = this.result;
                                        printerInfoHelper.appendImage(_temp_base64);
                                        if(btprinter_settings.printer_feed == 'Y'){
                                             printerInfoHelper.appendCutpage();
                                        }
                                        var jsonStr = printerInfoHelper.getPrinterInfoJsonString();
                                        //console.log(jsonStr);
                                        printerHelper.setPrinterInfoAndPrinter(function(){
                                            _p++;
                                            if(_p >= data.length){
                                                dialog.hide();
                                            }
                                        }, failedCallBack, jsonStr);
                                    }
                                    reader.readAsDataURL(file);
                                });
                            }, function(error){
                                window.parent.showAlert('File Read Error Code : '+error.code);
                            });
                        });

                    }, failedCallBack, btprinter_settings.printer_uuid); //Printer001

                }

                function failedCallBack(msg){
                    console.error(msg);
                    $rootScope.showAlert(msg);
                }

                function openDialog(data) {
                    $mdDialog.dialog(
                        'module/moduleMobile/program/mobile14/mobile14.html',
                        function(dialog){
                            return {
                                css_url:'module/moduleMobile/program/mobile14/mobile14.css',
                                isMobile:window.cordova!=undefined,
                                rpt_detail:data.rpt_detail,
                                btprinter:data.btprinter,
                                showbtprinter:data.showbtprinter,
                                btprint_setting:function(){
                                    $mdDialog.serviceDialog('BTPrinterSetting', {});
                                },
                                back: function () {
                                    dialog.hide();
                                },
                                confirm: function (item) {
                                    var msg = '';
                                    if(msg == ''){
                                        $MMWService.sendToServer({
                                            uri: 'ServicesSTD.Module_WIP.define_report_pdf_get',
                                            content : {
                                                printer_type:dialog.btprinter?'1':'0',
                                                rpt_name:item.Rpt_name,
                                                plot_no:options.plotItem.plot_no
                                            },
                                            success : function(data){
                                                if(data.url_pdf){
                                                    data.file_path = 'http://'+config.server.ip+':'+config.server.port+data.url_pdf;
                                                    data.width = 0;
                                                    data.height = 0;
                                                } else {
                                                    data.file_path = 'http://'+config.server.ip+':'+config.server.port+data.file_path;
                                                }
                                                if(window.nodeRequire){
                                                    printLabelWin(data, dialog);
                                                } else if(window.cordova){
                                                    if(dialog.btprinter){
                                                        downloadBTLabelFile(data, dialog);
                                                    } else {
                                                        printLabelMobile(data, dialog);
                                                    }
                                                } else {
                                                    printLabel(data, dialog);
                                                }
                                            }
                                        });
                                    } else {
                                        $rootScope.showAlert(msg);
                                    }
                                }
                            };
                        }
                    );
                }

                // 取得自定義報表
                (function getCheckList(){
                    $MMWService.sendToServer({
                        uri: 'ServicesSTD.Module_WIP.define_report_info_get',
                        content : {
                            parameters:[]
                        },
                        success : function(data){
                            if(window.cordova){
                                data.btprinter = true;
                                data.showbtprinter = true;
                            }
                            openDialog(data);
                        }
                    });
                })();
            };
        }]);
});
